from django.core.serializers import json
from django.shortcuts import render,redirect
from django.urls import reverse
from django.http import HttpResponse,JsonResponse
from common import check_code
from io import BytesIO
from django.views.generic import View
from django.core.mail import send_mail
from user.models import Info
import re
from itsdangerous import TimedJSONWebSignatureSerializer as tr
from peanut_Django import settings
from django.contrib.auth import authenticate,login,logout
# Create your views here.



# 获取验证码
class GetCheckCodeView(View):
    def get(self,request):
        code = check_code.getCheckChar()
        img = check_code.getImg(code)
        f = BytesIO()
        img.save(f, 'PNG')
        request.session['check_code'] = code
        return HttpResponse(f.getvalue())
    def post(self,request):
        ...


class RegisterView(View):
    def get(self,request):
        return redirect(reverse('cars:index'))

    def post(self,request):
        # 2、获取前端页面的数据
        user_name = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        email = request.POST.get('email')
        # 2.1 判断数据是否为空
        if not all([user_name, password, password2, email]):
            return render(request, 'index.html')

        # 2.2判断邮箱是否符合规范
        if not re.match(r'^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$', email):
            return render(request, 'index.html', {'errmsg': '邮箱不符合规范'})

        # 2.3判断重复的操作
        # 2.3.1判断邮箱
        try:
            print('进入try')
            user = Info.objects.filter(email__exact=email)
            print(user)

        except Exception as e:
            user = None

        if user:
            return render(request, 'index.html', {'errmsg': '邮箱已经被使用'})

        # 2.3.2 判断用户名
        try:
            user = Info.objects.get(username=user_name)
        except Exception as e:
            user = None
        if user:
            return render(request, 'index.html', {'errmsg': '用户名已经被使用'})

        # 3.1 创建一个用户对象
        user = Info.objects.create_user(username=user_name, email=email, password=password)
        # create_user(self, username, email=None, password=None,
        # 3.2 将激活标志设置未0
        Info.objects.select_related('')
        user.is_active = 0
        # 3.3 将用户对象保存到数据库中
        user.save()
        print('提交成功')



        # 授权码 xiameimei123
        # 4\设置激活链接，并对关键信息进行加密操作
        # 4.0加密
        # 设置秘钥
        # SECRET_KEY = 'fkku7vj#x(o@ilr_u(jzh20q@lyi522%!0)qpg0_p0e2^xw49&'

        t = tr(settings.SECRET_KEY,3600)
        # def __init__(self, secret_key, expires_in=None, **kwargs):

        user_id_dict = {'user_id':user.id}

        active_id = t.dumps(user_id_dict)
        # dumps(self, obj, salt=None, header_fields=None)
        active_id = active_id.decode()
        # 在主程序里面调用
        from celery_tasks.tasks import send_email_celery

        send_email_celery(to_email=email, active_id=active_id)


        # def send_mail(subject, message, from_email, recipient_list,
        #               fail_silently=False, auth_user=None, auth_password=None,
        #               connection=None, html_message=None):

        return redirect(reverse('cars:index'))


class ActiveHandler(View):
    def get(self,request,obj):
        # UserInfo.objects.get(id=user_id)
        print(request)
        print(obj)
        # SECRET_KEY = 'fkku7vj#x(o@ilr_u(jzh20q@lyi522%!0)qpg0_p0e2^xw49&'

        t = tr(settings.SECRET_KEY, 3600)
        try:
            user_id = t.loads(obj)
            userid = user_id['user_id']
            user = Info.objects.get(id=userid)
            user.is_active = 1
            user.save()
            return render(request,'index.html')
        except Exception as e:
            return HttpResponse('激活失败，请充值')


class LoginView(View):
    def get(self,request):
        ...
    def post(self,request):
        req = request.POST
        username = request.POST.get('username')
        password = request.POST.get('password')
        print(username)
        print(password)
        print(req)

        if not all([username,password]):
            response = JsonResponse({'status':100,'msg':'用户名密码不得为空'})
            return response

        user = authenticate(username=username, password=password)
        if user:
            response = JsonResponse({'status':200})
            response.set_cookie('username', username, 3600)
            return response

        else:
            return JsonResponse({'status':100,'msg':'用户名密码错误，请重新登陆'})


class LoginOutView(View):
    def get(self,request):
        response = redirect(reverse('cars:index'))
        response.delete_cookie('username')
        logout(request)
        return response
    def post(self,request):
        ...
